package com.seek.service.imp;

import java.util.List;

import java.util.Map;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.seek.core.BaseServiceImpl;
import com.seek.dao.CustomerAddrbookDao;
import com.seek.model.entity.TCustomerAddrbook;
import com.seek.service.CustomerAddrbookService;

@Repository("customerAddrbookService")
public class CustomerAddrbookServiceImpl extends BaseServiceImpl<TCustomerAddrbook> implements
    CustomerAddrbookService {

  @Autowired
  public void setDao(CustomerAddrbookDao customerAddrbookDao) {
    super.setDao(customerAddrbookDao);
  }

  public CustomerAddrbookDao getDao() {
    return (CustomerAddrbookDao) super.getDao();
  }

  @Transactional
  public void saveBatch(List<TCustomerAddrbook> datas, String custId) throws Exception {
    if (datas == null || datas.size() < 1) {
      return;
    }
    if (datas.get(0).getAddrType() == 1) {
      String sql = "update t_customer set has_elinkman=1 where id=?";
      this.getDao().executeUpdateSql(sql, new Object[]{custId});
      sql = "delete from t_customer_addrbook where customer_id=? and addr_type=1";
      this.getDao().executeUpdateSql(sql, new Object[]{custId});
    }

    for (TCustomerAddrbook en : datas) {
      this.getDao().insert(en);
    }
  }

  @Override
  @Transactional
  public void updateCallCountsBatch(Map<String, TCustomerAddrbook> map) throws Exception {
    if (MapUtils.isEmpty(map)) {
      return;
    }

    for (Map.Entry<String, TCustomerAddrbook> entry : map.entrySet()) {
      TCustomerAddrbook addrbook = entry.getValue();
      if (addrbook.getCallsNumber() > 0) {
        this.getDao()
            .executeUpdateSql("update t_customer_addrbook set calls_number = ? where id = ? ",
                new Object[]{addrbook.getCallsNumber(), addrbook.getId()});
      }
    }
  }
}